package com.xianggu.demo.service;

import com.xianggu.spring.aware.BeanPostProcessor;
import com.xianggu.spring.annotation.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

/**
 * @author chengjy
 * @date 2025/2/28
 */
@Component
public class OrderPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(String beanName, Object bean) {
        if("orderService".equals(beanName)){
            System.out.println("初始化前……"+ beanName);
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(String beanName, Object bean) {
        if("orderService".equals(beanName)){
            System.out.println("初始化后……"+ beanName);
        }

        if("bookService".equals(beanName)){
            // 类加载器的classLoader / 当前要代理的类所实现的接口 / 代理方法
            Object o = Proxy.newProxyInstance(this.getClass().getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    if(!"toString".equals( method.getName())){
                        System.out.println(String.format( " %s 方法执行中…… 方法参数[%s]", method.getName()  ,  args == null ? "null" : Arrays.toString(args)));
                    }

                    Object result = method.invoke(bean, args);
                    return result;
                }
            });
            return o;
        }
        return bean;
    }
}
